package com.qf.utils;

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.*;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @Author:LGD
 * @Date:2023/7/10 18:35
 */

@Data
@ConfigurationProperties(prefix = "qiniu")
@Component
public class QiNiuUpload {
    private String url;
    private String ak;
    private String sk;
    private String buket;


    /**
     * @param file 上传的图片
     * @return 返回上传后图片的地址
     */
    public String upload(MultipartFile file) throws Exception {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huadongZheJiang2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = UUID.randomUUID().toString();
        //将上传的文件file转为字节数组实现上传
        byte[] uploadBytes = file.getBytes();
        Auth auth = Auth.create(ak, sk);
        String upToken = auth.uploadToken(buket);
        Response response = uploadManager.put(uploadBytes, key, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        //返回文件的外链地址
        return url + key;
    }
}
